<?php
namespace Tbf\Component\Excel;
use Symfony\Component\HttpFoundation\StreamedResponse;
use Tbf\Component\Excel\Exporter\CsvExporter;
use Tbf\Component\Excel\Importer\CsvImporter;
use Tbf\Component\Http\SymfonyHttpFunction;
use Tbf\Component\Arrays\ArrayReaderInterface;
use Tbf\Component\Arrays\ArrayWriterInterface;
use Tbf\Component\Io\EchoStringWriter;
use Tbf\Component\Io\EncodingConvertStringWriter;
use Tbf\Component\Io\FileStringWriter;
use Tbf\Component\Io\StringReaderInterface;
use Tbf\Component\Io\StringWriterInterface;

/**
 * csv流式处理
 */
class StreamCsvFunction {
    /**
     * 将数组转成csv字符串
     * @param array $data [][]string
     * @param $file_path
     * @return string error
     */
    public static function fromArray(ArrayReaderInterface $reader,StringWriterInterface $writer){
        $obj = new CsvExporter();
        return $obj->export($reader,$writer);
    }
    public static function getResponseFromArrayAndEncoding(ArrayReaderInterface $reader,$encoding='UTF-8'){
        $writer = new EchoStringWriter();
        if ($encoding!=='UTF-8'){
            $writer = new EncodingConvertStringWriter($writer,'UTF-8',$encoding);
        }
        $resp = new StreamedResponse(function()use($reader,$writer){
            StreamCsvFunction::fromArray($reader,$writer);
        });
        $file_name = date('Y-m-d_H-i-s').'.csv';
        SymfonyHttpFunction::addAttachmentHeader($resp,'application/csv',$file_name);
        return $resp;

    }
    public static function saveFileFromArrayAndEncoding($file_path,ArrayReaderInterface $reader,$encoding='UTF-8'){
        $writer = new FileStringWriter($file_path);
        if ($encoding!=='UTF-8'){
            $writer = new EncodingConvertStringWriter($writer,'UTF-8',$encoding);
        }
        StreamCsvFunction::fromArray($reader,$writer);
    }
    public static function toArray(StringReaderInterface $reader,ArrayWriterInterface $writer){
        $obj = new CsvImporter();
        return $obj->import($reader,$writer);
    }
}